﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using WebApi2017.Models;

namespace WebApi2017.Controllers
{
    public class ProductsAPIController : ApiController
    {
        static readonly ProductRepository repository = new ProductRepository();

        public async Task<IHttpActionResult> GetAllProducts()
        {
            return Ok(await repository.GetAll());
        }

        public async Task<IHttpActionResult> GetProduct(int id)
        {
            Product item = await repository.Get(id);
            return Ok(item);
        }

        public async Task<IHttpActionResult> PostProduct(Product item)
        {
            item = await repository.Add(item);
            return CreatedAtRoute("DefaultApi", new { id = item.Id }, item);
        }

        public async Task<IHttpActionResult> PutProduct(int id, Product product)
        {
            product.Id = id;
            if (await repository.Update(product))
            {
                return StatusCode(HttpStatusCode.NoContent);
            }
            return NotFound();
        }
        public async Task<IHttpActionResult> PatchProduct(int id, Product product)
        {
            product.Id = id;
            if (await repository.Update(product))
            {
                return StatusCode(HttpStatusCode.NoContent);
            }
            return NotFound();
        }

        public async Task<IHttpActionResult> DeleteProduct(int id)
        {
            if (id == 1)
            {
                return BadRequest("不能删除ID为1的数据");//返回错误
            }
            await repository.Remove(id);
            return StatusCode(HttpStatusCode.NoContent);
        }
    }
}